<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :span="6">
            <a-form-item label="采购单号">
              <a-input placeholder="请输入采购单号" v-model="queryParam.purchaseNo" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="物料编码">
              <a-input placeholder="请输入物料编码" v-model="queryParam.materialCode" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="物料名称">
              <a-input placeholder="请输入物料名称" v-model="queryParam.materialName" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="供应商">
              <j-select-supplier-modal v-model="queryParam.supplier" placeholder="请选择供应商" />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="状态">
              <j-dict-select-tag
                placeholder="请选择状态"
                v-model="queryParam.status"
                dictCode="purchase_order_status"
                allowClear
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="退换货状态">
              <j-dict-select-tag
                placeholder="请选择退换货状态"
                v-model="queryParam.returnExchangeStatus"
                dictCode="return_exchange_status"
                allowClear
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="审核时间">
              <a-range-picker
                v-model="approveTimeRange"
                style="width: 100%"
                format="YYYY-MM-DD"
                :placeholder="['开始日期', '结束日期']"
                @change="onApproveTimeRangeChange"
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="审核人">
              <a-input placeholder="请输入审核人" v-model="queryParam.approveName" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button style="margin-left: 8px" @click="searchReset" icon="reload">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="handleAdd" v-if="hasPermission('wms:purchase:add')">新增</a-button>
      <a-button type="primary" icon="download" @click="handleExport" v-if="hasPermission('wms:purchase:export')"
        >导出</a-button
      >
      <a-upload
        name="file"
        :showUploadList="false"
        :multiple="false"
        :headers="tokenHeader"
        :action="importExcelUrl"
        @change="handleImportExcel"
        v-if="hasPermission('wms:purchase:import')"
      >
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel" v-if="hasPermission('wms:purchase:delete')">
            <a-icon type="delete" />删除
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px" @click="batchDel" v-if="hasPermission('wms:purchase:delete')">
          批量操作
          <a-icon type="down" />
        </a-button>
      </a-dropdown>
    </div>

    <!-- 数据表格 -->
    <div>
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        @change="handleTableChange"
        :scroll="{ x: 1200 }"
      >
        <!-- 状态列 -->
        <template slot="statusSlot" slot-scope="text">
          <a-tag :color="getStatusColor(text)">
            <j-dict-tag :value="text" dictCode="purchase_order_status" />
          </a-tag>
        </template>

        <!-- 退换货状态列 -->
        <template slot="returnExchangeStatusSlot" slot-scope="text, record">
          <a-tag :color="getReturnExchangeStatusColor(text)" v-if="text == 0 || text == 1">
            {{ text == 0 ? '无需处理' : '等待处理' }}
          </a-tag>
          <a v-else-if="text == 2" @click="handleOpenReturnExchangeModal(record, 2)">
            <a-tag color="red">
              退货单
            </a-tag>
          </a>
          <a v-else-if="text == 3" @click="handleOpenReturnExchangeModal(record, 3)">
            <a-tag color="blue">
              换货单
            </a-tag>
          </a>
          <span v-else>-</span>
        </template>

        <!-- 是否自动生成列 -->
        <template slot="autoGeneratedSlot" slot-scope="text">
          <a-tag :color="text ? 'blue' : 'green'">{{ text ? '自动生成' : '手动创建' }}</a-tag>
        </template>

        <!-- 是否执行完成列 -->
        <template slot="isCompletedSlot" slot-scope="text">
          <a-tag :color="text ? 'green' : 'red'">{{ text ? '是' : '否' }}</a-tag>
        </template>

        <!-- 操作列 -->
        <template slot="action" slot-scope="text, record">
          <a @click="handleDetail(record)">查看</a>

          <template v-if="record.status == 1">
            <a-divider type="vertical" />
            <a @click="handleEdit(record)" v-if="hasPermission('wms:purchase:edit')">编辑</a>
            <a-divider type="vertical" />
            <a @click="handleSubmit(record)" v-if="hasPermission('wms:purchase:edit')">提交审批</a>
            <a-divider type="vertical" />
            <a @click="handleDelete(record)" v-if="hasPermission('wms:purchase:delete')">删除</a>
          </template>

          <template v-if="record.status == 2">
            <a-divider type="vertical" />
            <a @click="handleApprove(record)" v-if="hasPermission('wms:purchase:approve')">审批</a>
          </template>

          <!-- 审批通过后显示打印和导出PDF按钮 -->
          <template v-if="record.status == 3 || record.status == 4 || record.status == 5 || record.status == 8">
            <a-divider type="vertical" />
            <a @click="handlePrint(record)">打印</a>
            <template v-if="record.status == 3 ||record.status == 8">
              <a-divider type="vertical" />
              <a @click="handleArrival(record)" v-if="hasPermission('wms:purchase:arrival')">采购到货</a>
            </template>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 表单区域 -->
    <purchase-order-modal ref="modalForm" @ok="modalFormOk"></purchase-order-modal>
    <purchase-order-detail ref="detailModal" @refresh="loadData"></purchase-order-detail>
    <purchase-approve-modal ref="approveModal" @ok="modalFormOk"></purchase-approve-modal>
    <purchase-inbound-modal ref="inboundModal" @ok="modalFormOk"></purchase-inbound-modal>
    <purchase-print-modal ref="printModal"></purchase-print-modal>
    <purchase-arrival-modal ref="arrivalModal" @ok="modalFormOk"></purchase-arrival-modal>
    <return-exchange-detail-modal ref="returnExchangeModal"></return-exchange-detail-modal>
  </a-card>
</template>

<script>
import { getAction, postAction, putAction, deleteAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import JDictSelectTag from '@/components/dict/JDictSelectTag'
import JDate from '@/components/jeecg/JDate'
import JDictTag from '@/components/dict/JDictTag'
import PurchaseOrderModal from './modules/PurchaseOrderModal.vue'
import PurchaseOrderDetail from './modules/PurchaseOrderDetail.vue'
import PurchaseApproveModal from './modules/PurchaseApproveModal.vue'
import PurchasePrintModal from './modules/PurchasePrintModal.vue'
import JSelectSupplierModal from '@/components/jeecgbiz/JSelectSupplierModal'
import PurchaseInboundModal from './modules/PurchaseInboundModal.vue'
import moment from 'moment'
import { USER_AUTH, SYS_BUTTON_AUTH } from '@/store/mutation-types'
import Vue from 'vue'
import PurchaseArrivalModal from './modules/PurchaseArrivalModal.vue'
import ReturnExchangeDetailModal from './modules/ReturnExchangeDetailModal.vue'

export default {
  name: 'PurchaseOrderList',
  mixins: [JeecgListMixin],
  components: {
    JDictSelectTag,
    JDate,
    JDictTag,
    PurchaseOrderModal,
    PurchaseOrderDetail,
    PurchaseApproveModal,
    PurchasePrintModal,
    PurchaseInboundModal,
    PurchaseArrivalModal,
    JSelectSupplierModal,
    ReturnExchangeDetailModal
  },
  computed: {
    importExcelUrl() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
    tokenHeader() {
      return {
        'X-Access-Token': Vue.ls.get('Access-Token'),
      }
    },
  },
  data() {
    return {
      description: '采购单管理页面',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '采购单号',
          align: 'center',
          dataIndex: 'purchaseNo',
          width: 160,
        },
        {
          title: '总金额',
          align: 'center',
          dataIndex: 'totalAmount',
          width: 100,
          customRender: (text) => {
            return text ? '¥' + parseFloat(text).toFixed(2) : '¥0.00'
          },
        },
        {
          title: '预计到货日期',
          align: 'center',
          dataIndex: 'expectedArrivalDate',
          width: 120,
          customRender: (text) => {
            return text ? moment(text).format('YYYY-MM-DD') : '-'
          },
        },
        {
          title: '是否自动生成',
          align: 'center',
          dataIndex: 'isAutoGenerated',
          width: 100,
          scopedSlots: { customRender: 'autoGeneratedSlot' },
        },
        {
          title: '是否执行完成',
          align: 'center',
          dataIndex: 'isCompleted',
          width: 100,
          scopedSlots: { customRender: 'isCompletedSlot' },
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'status',
          width: 100,
          scopedSlots: { customRender: 'statusSlot' },
        },
        {
          title: '退换货状态',
          align: 'center',
          dataIndex: 'returnExchangeStatus',
          width: 120,
          scopedSlots: { customRender: 'returnExchangeStatusSlot' },
        },
        {
          title: '审核人',
          align: 'center',
          dataIndex: 'approveName',
          width: 120,
        },
        {
          title: '审核时间',
          align: 'center',
          dataIndex: 'approveTime',
          width: 160,
          customRender: (text) => {
            return text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : '-'
          },
        },
        {
          title: '创建时间',
          align: 'center',
          dataIndex: 'createTime',
          width: 160,
          sorter: true,
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          width: 180,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/wms/purchase/list',
        delete: '/wms/purchase/delete',
        deleteBatch: '/wms/purchase/deleteBatch',
        exportXlsUrl: '/wms/purchase/exportXls',
        importExcelUrl: 'wms/purchase/importExcel',
      },
      dictOptions: {},
      superFieldList: [],
      toggleSearchStatus: false,
      permissionList: [],
      approveTimeRange: [], // 审核时间范围
    }
  },
  created() {
    // 加载权限列表
    this.loadPermissionData()

    // 页面加载时重置查询条件
    this.searchReset()
  },
  methods: {
    // 加载权限
    loadPermissionData() {
      // 从sessionStorage获取权限
      let authList = JSON.parse(sessionStorage.getItem(USER_AUTH) || '[]')

      // 如果sessionStorage中没有权限，尝试从localStorage获取
      if (!authList || authList.length == 0) {
        authList = JSON.parse(localStorage.getItem(USER_AUTH) || '[]')
      }

      // 从按钮权限中获取
      const buttonAuth = JSON.parse(
        sessionStorage.getItem(SYS_BUTTON_AUTH) || localStorage.getItem(SYS_BUTTON_AUTH) || '[]'
      )

      // 合并权限
      if (buttonAuth && buttonAuth.length > 0) {
        authList = authList.concat(buttonAuth)
      }

      // 提取action字段
      this.permissionList = authList.map((auth) => auth.action || auth)
    },
    getStatusColor(status) {
      // 状态颜色映射
      const statusColorMap = {
        1: 'blue', // 草稿
        2: 'orange', // 待审批
        3: 'green', // 已审批
        4: 'cyan', // 部分入库
        5: 'purple', // 已完成
        6: 'red', // 已取消
        7: 'blue', // 已到货
        8: 'orange', // 部分到货
      }
      return statusColorMap[status] || 'default'
    },
    getReturnExchangeStatusColor(status) {
      // 退换货状态颜色映射
      const statusColorMap = {
        0: 'green', // 无需退换货
        1: 'orange', // 等待处理
        2: 'red', // 退货
        3: 'blue', // 换货
      }
      return statusColorMap[status] || 'default'
    },
    handleToggleSearch() {
      this.toggleSearchStatus = !this.toggleSearchStatus
    },
    handleDetail(record) {
      this.$refs.detailModal.show(record.id)
      this.$refs.detailModal.title = '查看采购单'
    },
    handleSubmit(record) {
      this.$confirm({
        title: '确认提交',
        content: `确定提交采购单 ${record.purchaseNo} 进行审批吗？`,
        onOk: () => {
          return postAction('/wms/purchase/submit?id=' + record.id).then((res) => {
            if (res.success) {
              this.$message.success('提交成功')
              this.loadData()
            } else {
              this.$message.error(res.message || '提交失败')
            }
          })
        },
      })
    },
    handleApprove(record) {
      this.$refs.approveModal.show(record)
      this.$refs.approveModal.title = '审批采购单'
    },
    handleInbound(record) {
      this.$refs.inboundModal.show(record.id)
      this.$refs.inboundModal.title = '采购入库'
    },
    handlePrint(record) {
      this.$refs.printModal.show(record.id)
      this.$refs.printModal.title = '打印采购单'
    },
    handleArrival(record) {
      this.$refs.arrivalModal.show(record.id)
      this.$refs.arrivalModal.title = '采购到货'
    },
    handleExport() {
      this.handleExportXls('采购单')
    },
    // 删除单个采购单
    handleDelete(record) {
      this.$confirm({
        title: '确认删除',
        content: `确定删除采购单 ${record.purchaseNo} 吗？`,
        onOk: () => {
          return deleteAction(this.url.delete, { id: record.id }).then((res) => {
            if (res.success) {
              this.$message.success('删除成功')
              this.loadData()
            } else {
              this.$message.error(res.message || '删除失败')
            }
          })
        },
      })
    },
    // 批量删除采购单
    batchDel() {
      if (this.selectedRowKeys.length == 0) {
        this.$message.warning('请选择至少一条记录')
        return
      }

      this.$confirm({
        title: '确认删除',
        content: '确定删除选中的采购单吗？',
        onOk: () => {
          return deleteAction(this.url.deleteBatch, { ids: this.selectedRowKeys.join(',') }).then((res) => {
            if (res.success) {
              this.$message.success('批量删除成功')
              this.loadData()
              this.onClearSelected()
            } else {
              this.$message.error(res.message || '批量删除失败')
            }
          })
        },
      })
    },
    // 重写 handleEdit 方法，确保正确调用 modalForm 的 edit 方法
    handleEdit(record) {
      this.$refs.modalForm.edit(record)
      this.$refs.modalForm.title = '编辑采购单'
    },
    // 处理导入Excel文件
    handleImportExcel(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status == 'done') {
        if (info.file.response.success) {
          this.$message.success(`${info.file.name} 文件上传成功`)
          this.loadData()
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.message}.`)
        }
      } else if (info.file.status == 'error') {
        this.$message.error(`文件上传失败: ${info.file.response.message}`)
      }
    },
    // 判断是否有权限
    hasPermission(permission) {
      if (!permission) return true // 如果未指定权限，默认有权限

      // 检查权限列表中是否包含指定权限
      if (this.permissionList.includes(permission)) {
        return true
      }

      // 检查权限列表中是否包含以逗号分隔的多个权限
      for (let perm of this.permissionList) {
        if (perm && perm.includes(',')) {
          const perms = perm.split(',')
          if (perms.includes(permission)) {
            return true
          }
        }
      }

      return false
    },
    // 在methods部分添加handleExportPDF方法
    handleExportPDF(record) {
      this.$refs.printModal.show(record.id)
      this.$refs.printModal.title = '导出采购单PDF'

      // 延迟调用导出PDF方法，确保数据加载完成
      setTimeout(() => {
        this.$refs.printModal.exportPDF()
      }, 1000)
    },
    // 处理审核时间范围变化
    onApproveTimeRangeChange(date, dateString) {
      this.queryParam.approveTimeStart = dateString[0];
      this.queryParam.approveTimeEnd = dateString[1];
    },
    // 重置按钮
    searchReset() {
      this.queryParam = {}
      this.approveTimeRange = []
      this.loadData(1);
    },
    // 表格分页、排序、筛选变化
    handleTableChange(pagination, filters, sorter) {
      // 默认按照创建时间倒序排序
      if (!sorter || Object.keys(sorter).length == 0) {
        this.isorter.column = 'createTime';
        this.isorter.order = 'desc';
      } else {
        this.isorter.column = sorter.field;
        this.isorter.order = sorter.order == 'ascend' ? 'asc' : 'desc';
      }
      this.ipagination = pagination;
      this.loadData();
    },
    // 打开退换货单详情
    handleOpenReturnExchangeModal(record, status) {
      this.$refs.returnExchangeModal.show(record.id, status)
      this.$refs.returnExchangeModal.title = '退换货单详情'
    }
  },
}
</script>

<style scoped>
@import '~@assets/less/common.less';
</style> 